<template>
  <a-input 
    ref="inputRef"
    :value="name" 
    @update:value="updateName" 
    placeholder="请输入名称" 
    :maxLength="maxLength" 
    allowClear 
  />
  <div class="dynamic-packet">
    插入动态词包：<span v-for="item in dynamicPacket" :key="item" @click="appendWord(item)">【{{ item }}】</span>
  </div>
  <a-form-item-rest>
    <a-checkbox style="margin-top: 10px" :checked="auto_suffix_id" @update:checked="updateAutoSuffixId"> 加入随机ID后缀 </a-checkbox>
  </a-form-item-rest>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick } from "vue";

// 修改props定义，使用独立的name和auto_suffix_id，添加maxLength属性
const props = defineProps({
  name: {
    type: String,
    default: "",
  },
  auto_suffix_id: {
    type: Boolean,
    default: false,
  },
  maxLength: {
    type: Number,
    default: 50,
  },
});

// 修改emit事件名称
const emit = defineEmits(["update:name", "update:auto_suffix_id"]);

// 定义更准确的类型
interface InputInstance {
  focus: () => void;
  blur: () => void;
  [key: string]: any;
}

// 使用更精确的类型
const inputRef = ref<InputInstance | null>(null);

// 动态词包
const dynamicPacket = reactive([
  "项目名称",
  "账户标签",
  "账户备注",
  "创建日期",
  "创建时间",
  "定向包名",
  "标题包名",
  "营销目标",
  "下发日期",
  "下发日期时间",
]);

// 更新名称
const updateName = (val: string) => {
  emit("update:name", val);
};

// 更新自动后缀ID
const updateAutoSuffixId = (val: boolean) => {
  emit("update:auto_suffix_id", val);
};

// 插入动态词包
const appendWord = (word: string) => {
  // 如果当前名称为空，设置一个空格避免验证错误
  const currentName = props.name || "";
  const newValue = currentName + `[${word}]`;
  
  // 先更新值
  updateName(newValue);
  
  // 等待DOM更新完成
  nextTick(() => {
    // 首先让输入框获得焦点
    if (inputRef.value?.focus) {
      inputRef.value.focus();
      
      // 然后立即通过延时让输入框失去焦点
      setTimeout(() => {
        if (inputRef.value?.blur) {
          console.log("先聚焦后失焦");
          inputRef.value.blur();
        }
      }, 50);
    }
  });
};
</script>

<style scoped lang="less">
.dynamic-packet {
  background-color: #f0f0f0;
  padding: 5px 15px;
  margin-top: 10px;
}
.dynamic-packet span {
  cursor: pointer;
  color: #1890ff;
}
</style>
